package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ShopMapper shopMapper;
    @Autowired
    private CacheClient cacheClient;
    String key="cache:shop:";
    String keyPrefix="lock:shop:";

    /**
     * 查询店铺
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result queryById(Long id) {
        Shop shop = cacheClient.queryWithMutex(keyPrefix,id,Shop.class,(ids)->shopMapper.queryById(id),30L,TimeUnit.MINUTES);
        if(shop==null){
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    /**
     * 更新店铺
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        //1.更新数据库
        shopMapper.updateShop(shop);
        //2.删除缓存
        redisTemplate.delete(key + id);
        return Result.ok();
    }

}
